﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.IO;
using TanHungViet.Web.Models;
using TanHungViet.Helper;
using log4net;

namespace TanHungViet.Web.Controllers
{
    public class QuanLyNoiDungController : Controller
    {
        #region Get/Set Session
        private string GetSession(string sessionName)
        {
            if (Session[sessionName] != null)
                return Session[sessionName].ToString();
            else
                return string.Empty;
        }

        private void SetSession(string sessionName, string sessionValue)
        {
            if (string.IsNullOrEmpty(sessionValue))
            {
                Session[sessionName] = null;
                return;
            }

            Session[sessionName] = sessionValue;
            Session.Timeout = 10;
        }
        #endregion

        private bool HaveUserRight()
        {
            return (!string.IsNullOrEmpty(GetSession("UserName")));
        }

        #region Dang nhap, Dang xuat, Doi mat khau
        public ActionResult DangNhap()
        {
            if (HaveUserRight())
                return RedirectToAction("Index");
            else
            {
                return View();
            }
        }

        [HttpPost()]
        public ActionResult DangNhap(FormCollection form)
        {
            string userName = Request["inpUserName"];
            string password = Request["inpPassword"];
            bool checkUserLogin = false;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                UserRepository userRepository = new UserRepository(entity);
                checkUserLogin = userRepository.CheckUserLogin(userName, password);
            }

            if (checkUserLogin)
            {
                SetSession("UserName", userName);
                return RedirectToAction("Index");
            }

            ViewData["Error"] = "Tên tài khoản hoặc mật khẩu không hợp lệ!!!!";
            return View();
        }

        public ActionResult DangXuat()
        {
            if (HaveUserRight())
                SetSession("UserName", null);

            return RedirectToAction("DangNhap");
        }

        public ActionResult DoiMatKhau()
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");
            else
            {
                return View();
            }
        }

        [HttpPost()]
        public ActionResult DoiMatKhau(FormCollection form)
        {
            string oldPwd = Request["inpOldPassword"];
            string oldPwd2 = Request["inpOldPassword2"];
            if (oldPwd != oldPwd2)
            {
                ViewData["Error"] = "Mật khẩu nhập lại không đúng!!!!";
                return View();
            }

            string newPwd = Request["inpNewPassword"];
            if (string.IsNullOrEmpty(newPwd) || newPwd.Length < 6)
            {
                ViewData["Error"] = "Mật khẩu tối thiểu phải có 6 ký tự!!!!";
                return View();
            }

            bool checkUserLogin = false;
            string userName = GetSession("UserName");
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                UserRepository userRepository = new UserRepository(entity);
                checkUserLogin = userRepository.CheckUserLogin(userName, oldPwd);
            }

            if (!checkUserLogin)
            {
                ViewData["Error"] = "Mật khẩu nhập vào không chính xác!!!!";
                return View();
            }

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                UserRepository userRepository = new UserRepository(entity);
                userRepository.ChangePassword(userName, newPwd);
                SetSession("UserName", null);
            }
            return RedirectToAction("DangNhap");
        }
        #endregion

        public ActionResult Index()
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            List<MenuItem> model = new List<MenuItem>();
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                string cultureInfo = "";
                model = menuRepository.GetDynamicMenu(cultureInfo, false);
                model.AddRange(menuRepository.GetDynamicMenu(cultureInfo, true));
            }

            string[] arrOneContent = new string[] { "Trang Chủ", "Tuyển Dụng", "Sitemap", "Liên Hệ", "Giới Thiệu", "Dịch Vụ", "Báo Giá" };

            for (int i = 0; i < model.Count; i++)
            {
                var item = model[i];
                if (arrOneContent.Contains<string>(item.Title))
                {
                    model.RemoveAt(i);
                    i--;
                }
            }
            return View(model);
        }

        #region Quan Ly Noi Dung
        public ActionResult QuanLyDSNoiDung(string code)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["ContentTitle"] = contentRepository.GetContentByCode(code, "").ContentTitle;
            }

            ViewData["SearchType"] = "Tên Nội Dung";
            ViewData["ContentType"] = code;
            return View();
        }

        public ActionResult DanhSachNoiDung(string code, string strPageIndex, string qTitle)
        {
            int pageSize = Constant.PageSize;
            int pageIndex = Convert.ToInt32(strPageIndex);

            List<Content> listContent;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType(code).ToList<Content>();
            }

            if (!string.IsNullOrEmpty(qTitle))
            {
                int i = 0;
                do
                {
                    var item = listContent[i];
                    string title2 = string.IsNullOrEmpty(item.ContentTitle2) ? string.Empty : item.ContentTitle2;
                    string qTitleVi = TanHungViet.Helper.Util.GenerateCodeByTitle(qTitle.ToLower());
                    string itemTitle = TanHungViet.Helper.Util.GenerateCodeByTitle(item.ContentTitle.ToLower());
                    if (itemTitle.Contains(qTitleVi) || title2.Contains(qTitle))
                    {
                        i++;
                        continue;
                    }

                    listContent.Remove(item);
                } while (i < listContent.Count);
            }

            //var model = source.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToArray();
            var model = listContent.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            int total = listContent.Count;
            ViewData["TotalPage"] = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1).ToString();
            ViewData["PageIndex"] = pageIndex.ToString();
            ViewData["PageSize"] = pageIndex.ToString();
            ViewData["ContentType"] = code;

            return View(model);
        }

        public ActionResult ThemSuaNoiDung(int code, string contentType)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            Content model = null;
            if (code == 0)
                model = new Content("", "", "", "", "", "", "", "", "", "");
            else if (code > 0)
            {
                using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
                {
                    ContentRepository contentRepository = new ContentRepository(entity);
                    model = contentRepository.GetFullContentByID(code);
                }
            }

            ViewData["ContentType"] = contentType;
            ViewData["ContentTitle"] = model.ContentTitle;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ThemSuaNoiDung(Content obj)
        {
            string contentType = Request.Form["content-type"];
            if (!ModelState.IsValid)
            {
                ViewData["ContentType"] = contentType;
                return RedirectToAction("ThemSuaNoiDung", new { code = obj.ContentID, contentType = contentType });
            }

            // tinh toan gia tri cho content-code va content-image-url
            obj.ContentCode = TanHungViet.Helper.Util.GenerateCodeByTitle(obj.ContentTitle.ToLower());
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);
            obj.ContentID = int.Parse(Request.Form["ContentID"]);

            string menuLink = string.Empty;
            bool addUpdateMenu = false;
            switch (contentType)
            {
                case Constant.CodeGioiThieu:
                    menuLink = "/GioiThieu/";
                    addUpdateMenu = true;
                    break;
                case Constant.CodeDichVu:
                    menuLink = "/DichVu/";
                    addUpdateMenu = true;
                    break;
                case Constant.CodeBaoGia:
                    menuLink = "/BaoGia/";
                    addUpdateMenu = true;
                    break;
            }

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                // them tin tuc moi
                if (obj.ContentID == 0)
                    contentRepository.AddNewContentFull(obj, contentType, addUpdateMenu, menuLink, false, false);
                else
                    contentRepository.UpdateContentFull(obj, addUpdateMenu, menuLink, false);
            }

            return RedirectToAction("Index");
        }

        public ActionResult XoaNoiDung(string code, bool isProject, bool deleteMenu)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            string imageName = string.Empty;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                imageName = contentRepository.DeleteContentsByListId(code, isProject, deleteMenu);
            }

            if (!string.IsNullOrEmpty(imageName))
            {
                string deleteFileName = Path.Combine(
                  Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                  Constant.ImageFolerContent),
                  imageName);
                System.IO.File.Delete(deleteFileName);
            }

            return Content("");
        }
        #endregion

        #region Quan Ly Tin Tuc, Tu Van, Hoi Dap
        public ActionResult QuanLyDSTinTuc(string code)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["ContentTitle"] = contentRepository.GetContentByCode(code, "").ContentTitle;
            }

            ViewData["SearchType"] = "Tên Nội Dung";
            ViewData["ContentType"] = code;
            return View();
        }

        public ActionResult DanhSachTinTuc(string code, string strPageIndex, string qTitle)
        {
            int pageSize = Constant.PageSize;
            int pageIndex = Convert.ToInt32(strPageIndex);

            List<Content> listContent;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType(code).ToList<Content>();
            }

            if (!string.IsNullOrEmpty(qTitle))
            {
                int i = 0;
                do
                {
                    var item = listContent[i];
                    string title2 = string.IsNullOrEmpty(item.ContentTitle2) ? string.Empty : item.ContentTitle2;
                    string qTitleVi = TanHungViet.Helper.Util.GenerateCodeByTitle(qTitle.ToLower());
                    string itemTitle = TanHungViet.Helper.Util.GenerateCodeByTitle(item.ContentTitle.ToLower());
                    if (itemTitle.Contains(qTitleVi) || title2.Contains(qTitle))
                    {
                        i++;
                        continue;
                    }

                    listContent.Remove(item);
                } while (i < listContent.Count);
            }

            //var model = source.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToArray();
            var model = listContent.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            int total = listContent.Count;
            ViewData["TotalPage"] = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1).ToString();
            ViewData["PageIndex"] = pageIndex.ToString();
            ViewData["PageSize"] = pageIndex.ToString();
            ViewData["ContentType"] = code;

            return View(model);
        }

        public ActionResult ThemSuaTinTuc(int code, string contentType)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            Content model = null;
            if (code == 0)
                model = new Content("", "", "", "", "", "", "", "", "", "");
            else if (code > 0)
            {
                using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
                {
                    ContentRepository contentRepository = new ContentRepository(entity);
                    model = contentRepository.GetFullContentByID(code);
                }
            }

            ViewData["ContentType"] = contentType;
            ViewData["ContentTitle"] = model.ContentTitle;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ThemSuaTinTuc(Content obj)
        {
            string contentType = Request.Form["content-type"];
            if (!ModelState.IsValid)
            {
                ViewData["ContentType"] = contentType;
                return RedirectToAction("ThemSuaTinTuc", new { code = obj.ContentID, contentType = contentType });
            }

            // tinh toan gia tri cho content-code va content-image-url
            obj.ContentCode = TanHungViet.Helper.Util.GenerateCodeByTitle(obj.ContentTitle.ToLower());
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);

            obj.ContentID = int.Parse(Request.Form["ContentID"]);
            HttpPostedFileBase file = Request.Files[0];
            string fileName = string.Empty;
            bool hasImage = false;
            if (file.ContentLength > 0)
            {
                fileName = obj.ContentID + ".";
                string[] temp = file.FileName.Split(new char[] { '.' });
                fileName += temp[1];
                obj.ContentImage = fileName;
                hasImage = true;
            }

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                if (obj.ContentID == 0)
                    contentRepository.AddNewContentFull(obj, contentType, false, "", hasImage, false);
                else
                    contentRepository.UpdateContentFull(obj, false, "", false);
            }

            // upload hinh anh
            if (file.ContentLength > 0)
            {
                string savedFileName = Path.Combine(
                   Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                   Constant.ImageFolerContent),
                   Path.GetFileName(obj.ContentImage));
                file.SaveAs(savedFileName);
            }

            return RedirectToAction("QuanLyDSTinTuc", new { code = contentType });
        }
        #endregion

        
        #region Quan Ly Du An
        public ActionResult QuanLyDSDuAn(string code)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["ContentTitle"] = contentRepository.GetContentByCode(code, "").ContentTitle;
            }

            ViewData["SearchType"] = "Tên Nội Dung";
            ViewData["ContentType"] = code;
            return View();
        }

        public ActionResult DanhSachDuAn(string code, string strPageIndex, string qTitle)
        {
            int pageSize = Constant.PageSize;
            int pageIndex = Convert.ToInt32(strPageIndex);

            List<Content> listContent;
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType(code).ToList<Content>();
            }

            if (!string.IsNullOrEmpty(qTitle))
            {
                int i = 0;
                do
                {
                    var item = listContent[i];
                    string title2 = string.IsNullOrEmpty(item.ContentTitle2) ? string.Empty : item.ContentTitle2;
                    string qTitleVi = TanHungViet.Helper.Util.GenerateCodeByTitle(qTitle.ToLower());
                    string itemTitle = TanHungViet.Helper.Util.GenerateCodeByTitle(item.ContentTitle.ToLower());
                    if (itemTitle.Contains(qTitleVi) || title2.Contains(qTitle))
                    {
                        i++;
                        continue;
                    }

                    listContent.Remove(item);
                } while (i < listContent.Count);
            }

            //var model = source.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToArray();
            var model = listContent.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            int total = listContent.Count;
            ViewData["TotalPage"] = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1).ToString();
            ViewData["PageIndex"] = pageIndex.ToString();
            ViewData["PageSize"] = pageIndex.ToString();
            ViewData["ContentType"] = code;

            return View(model);
        }

        public ActionResult ThemSuaDuAn(int code, string contentType)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            Content model = null;
            if (code == 0)
                model = new Content("", "", "", "", "", "", "", "", "", "");
            else if (code > 0)
            {
                using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
                {
                    ContentRepository contentRepository = new ContentRepository(entity);
                    model = contentRepository.GetFullContentByID(code);
                }
            }

            ViewData["ContentType"] = contentType;
            ViewData["ContentTitle"] = model.ContentTitle;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ThemSuaDuAn(Content obj)
        {
            string contentType = Request.Form["content-type"];
            if (!ModelState.IsValid)
            {
                ViewData["ContentType"] = contentType;
                return RedirectToAction("ThemSuaDuAn", new { code = obj.ContentID, contentType = contentType });
            }

            // tinh toan gia tri cho content-code va content-image-url
            obj.ContentCode = TanHungViet.Helper.Util.GenerateCodeByTitle(obj.ContentTitle.ToLower());
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            //obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);

            obj.ContentID = int.Parse(Request.Form["ContentID"]);
            HttpPostedFileBase file = Request.Files[0];
            string fileName = string.Empty;
            bool hasImage = false;
            if (file.ContentLength > 0)
            {
                fileName = obj.ContentID + ".";
                string[] temp = file.FileName.Split(new char[] { '.' });
                fileName += temp[1];
                obj.ContentImage = fileName;
                hasImage = true;
            }

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                if (obj.ContentID == 0)
                    contentRepository.AddNewContentFull(obj, contentType, false, "", hasImage, true);
                else
                    contentRepository.UpdateContentFull(obj, false, "", true);
            }

            // upload hinh anh
            if (file.ContentLength > 0)
            {
                string savedFileName = Path.Combine(
                   Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                   Constant.ImageFolerContent),
                   Path.GetFileName(obj.ContentImage));
                file.SaveAs(savedFileName);
            }

            return RedirectToAction("QuanLyDSDuAn", new { code = contentType });
        }
        #endregion

        #region Quan Ly Menu
        public ActionResult ThemMenu(string code)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            return View();
        }

        [HttpPost]
        public ActionResult ThemMenu(string code, FormCollection collection)
        {
            string title = collection["ContentTitle"];
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                menuRepository.AddNewMenu(title, code);
            }
            return RedirectToAction("Index");
        }

        public ActionResult SuaMenu(string code)
        {
            if (!HaveUserRight())
                return RedirectToAction("DangNhap");

            string cultureInfo = "";
            if (Session["CultureInfo"] != null)
                cultureInfo = Session["CultureInfo"].ToString();

            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                ViewData["MenuTitle"] = contentRepository.GetContentByCode(code, cultureInfo).ContentTitle;
            }

            return View();
        }

        [HttpPost]
        public ActionResult SuaMenu(string code, FormCollection collection)
        {
            string newTitle = collection["ContentTitle"];
            using (DBTanHungVietEntities entity = new DBTanHungVietEntities())
            {
                MenuRepository menuRepository = new MenuRepository(entity);
                menuRepository.UpdateMenu(code, newTitle);
            }

            return RedirectToAction("Index");
        }
        #endregion
    }
}
